import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { userApi } from '../api/user'

export const useUserStore = defineStore('user', () => {
  // 状态
  const userInfo = ref(null)
  const token = ref('')
  const isLoggedIn = computed(() => !!userInfo.value)
  const isAdmin = computed(() => userInfo.value?.userRole === 'admin')

  // 初始化用户信息（从localStorage恢复）
  const initUserInfo = () => {
    try {
      const savedUserInfo = localStorage.getItem('userInfo')
      const savedToken = localStorage.getItem('token')
      
      if (savedUserInfo) {
        userInfo.value = JSON.parse(savedUserInfo)
      }
      if (savedToken && savedToken !== 'undefined' && savedToken !== 'null') {
        token.value = savedToken
      } else {
        // 清理无效的 token
        localStorage.removeItem('token')
        token.value = ''
      }
    } catch (error) {
      console.error('初始化用户信息失败:', error)
      clearUserInfo()
    }
  }

  // 设置用户信息
  const setUserInfo = (userData) => {
    userInfo.value = userData
    token.value = userData.token || ''
    
    // 保存到localStorage（仅当 token 存在且有效时）
    if (userData.token) {
      localStorage.setItem('token', userData.token)
    } else {
      localStorage.removeItem('token')
    }
    localStorage.setItem('userInfo', JSON.stringify(userData))
  }

  // 清除用户信息
  const clearUserInfo = () => {
    userInfo.value = null
    token.value = ''
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
  }

  // 登录
  const login = async (loginData) => {
    try {
      const response = await userApi.login(loginData)
      if (response.code === 0) {
        setUserInfo(response.data)
        return { success: true, data: response.data }
      } else {
        throw new Error(response.message || '登录失败')
      }
    } catch (error) {
      console.error('登录失败:', error)
      return { success: false, message: error.message }
    }
  }

  // 注册
  const register = async (registerData) => {
    try {
      const response = await userApi.register(registerData)
      if (response.code === 0) {
        return { success: true, data: response.data }
      } else {
        throw new Error(response.message || '注册失败')
      }
    } catch (error) {
      console.error('注册失败:', error)
      return { success: false, message: error.message }
    }
  }

  // 注销
  const logout = async () => {
    try {
      // 调用后端注销接口
      await userApi.logout()
    } catch (error) {
      console.error('注销请求失败:', error)
    } finally {
      // 无论后端请求是否成功，都清除本地用户信息
      clearUserInfo()
    }
  }

  // 获取当前用户信息
  const getCurrentUser = async () => {
    try {
      const response = await userApi.getCurrentUser()
      if (response.code === 0) {
        // 更新用户信息，但保留token
        const currentToken = token.value
        setUserInfo({ ...response.data, token: currentToken })
        return { success: true, data: response.data }
      } else {
        throw new Error(response.message || '获取用户信息失败')
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      // 如果获取用户信息失败，可能是token过期，清除用户信息
      clearUserInfo()
      return { success: false, message: error.message }
    }
  }



  // 验证token有效性
  const verifyToken = async () => {
    if (!token.value) {
      return false
    }
    
    try {
      const response = await userApi.verifyToken()
      return response.code === 0 && response.data === true
    } catch (error) {
      console.error('Token验证失败:', error)
      clearUserInfo()
      return false
    }
  }

  // 检查用户权限
  const hasPermission = (requiredRole) => {
    if (!isLoggedIn.value) {
      return false
    }
    
    // 如果需要管理员权限
    if (requiredRole === 'admin') {
      return userInfo.value?.userRole === 'admin'
    }
    
    // 如果需要用户权限（默认权限）
    if (requiredRole === 'user') {
      return userInfo.value?.userRole === 'user' || userInfo.value?.userRole === 'admin'
    }
    
    // 默认返回true（无特殊权限要求）
    return true
  }

  // 检查是否为管理员
  const checkAdminRole = () => {
    return userInfo.value?.userRole === 'admin'
  }

  // 检查是否为普通用户
  const checkUserRole = () => {
    return userInfo.value?.userRole === 'user'
  }

  // 管理员功能：获取用户列表
  const getUserList = async (params) => {
    if (!isAdmin.value) {
      throw new Error('权限不足')
    }
    
    try {
      const response = await userApi.getUserList(params)
      if (response.code === 0) {
        return { success: true, data: response.data }
      } else {
        throw new Error(response.message || '获取用户列表失败')
      }
    } catch (error) {
      console.error('获取用户列表失败:', error)
      return { success: false, message: error.message }
    }
  }

  // 管理员功能：添加用户
  const addUser = async (userData) => {
    if (!isAdmin.value) {
      throw new Error('权限不足')
    }
    
    try {
      const response = await userApi.addUser(userData)
      if (response.code === 0) {
        return { success: true, data: response.data }
      } else {
        throw new Error(response.message || '添加用户失败')
      }
    } catch (error) {
      console.error('添加用户失败:', error)
      return { success: false, message: error.message }
    }
  }

  // 用户自己更新个人信息
  const updateSelfInfo = async (userData) => {
    try {
      const response = await userApi.updateSelfInfo(userData)
      if (response.code === 0) {
        // 更新成功后重新获取用户信息
        await getCurrentUser()
        return { success: true, data: response.data }
      } else {
        throw new Error(response.message || '更新个人信息失败')
      }
    } catch (error) {
      console.error('更新个人信息失败:', error)
      return { success: false, message: error.message }
    }
  }

  // 管理员功能：更新用户
  const updateUser = async (userData) => {
    if (!isAdmin.value) {
      throw new Error('权限不足')
    }
    
    try {
      const response = await userApi.updateUser(userData)
      if (response.code === 0) {
        return { success: true, data: response.data }
      } else {
        throw new Error(response.message || '更新用户失败')
      }
    } catch (error) {
      console.error('更新用户失败:', error)
      return { success: false, message: error.message }
    }
  }

  // 管理员功能：删除用户
  const deleteUser = async (userId) => {
    if (!isAdmin.value) {
      throw new Error('权限不足')
    }
    
    try {
      const response = await userApi.deleteUser(userId)
      if (response.code === 0) {
        return { success: true, data: response.data }
      } else {
        throw new Error(response.message || '删除用户失败')
      }
    } catch (error) {
      console.error('删除用户失败:', error)
      return { success: false, message: error.message }
    }
  }

  // 监听用户登录和注销事件
  if (typeof window !== 'undefined') {
    window.addEventListener('user-login', (event) => {
      setUserInfo(event.detail)
    })
    
    window.addEventListener('user-logout', () => {
      clearUserInfo()
    })
  }

  return {
    // 状态
    userInfo,
    token,
    isLoggedIn,
    isAdmin,
    
    // 方法
    initUserInfo,
    setUserInfo,
    clearUserInfo,
    login,
    register,
    logout,
    getCurrentUser,
    updateSelfInfo,
    verifyToken,
    hasPermission,
    checkAdminRole,
    checkUserRole,
    
    // 管理员方法
    getUserList,
    addUser,
    updateUser,
    deleteUser
  }
})